package com.example.queryexpressdelivery_01.fragment;

import android.os.Bundle;
import android.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.queryexpressdelivery_01.common.DeliveryDAL;
import com.example.queryexpressdelivery_01.common.HttpGetData;
import com.example.queryexpressdelivery_01.adapter.IndexRvAdapter;
import com.example.queryexpressdelivery_01.R;
import com.example.queryexpressdelivery_01.common.SharedViewModel;
import com.example.queryexpressdelivery_01.entity.FeedbackData;
import com.example.queryexpressdelivery_01.entity.TrackingResponse;
import com.example.queryexpressdelivery_01.entity.UserData;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TraceFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TraceFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private String sTitle;
    private String userid;
    private RecyclerView rvTraceData;
    private ImageView ivTraceDelete;
    private TextView tvTraceTitle;
    private HttpGetData httpGetData;
    private Gson gson = new Gson();
    IndexRvAdapter adapter = new IndexRvAdapter();
    public TraceFragment() {
        // Required empty public constructor
    }

    public TraceFragment(String sTitle, String userid) {
        this.sTitle = sTitle;
        this.userid = userid;
        Bundle d1 = new Bundle();
        d1.putString("param1", sTitle);
        d1.putString("id", userid);
        this.setArguments(d1);
    }

    public String getTitle() {
        return sTitle;
    }

    public String getUserid() {
        return userid;
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment TraceFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TraceFragment newInstance(String param1, String param2) {
        TraceFragment fragment = new TraceFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    public void onStart() {
        super.onStart();
        rvTraceData.setLayoutManager(new LinearLayoutManager(getContext()));
        DeliveryDAL deliveryDAL = new DeliveryDAL(getContext());
        SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        model.getTrackingData().observe(getViewLifecycleOwner(), trackingResponse -> {
            UserData userData = deliveryDAL.queryById(Integer.parseInt(userid));
            if (trackingResponse != null) {
                updateData(userData.getData()); // 使用新的 trackingResponse 更新数据
            }
        });
        UserData d = deliveryDAL.queryById(Integer.parseInt(userid));
        Log.i("TAG","能获得："+d.getData());
        if (d.getData()!=null){
            Log.i("TAG","开局进入");
            updateData(d.getData());
        }
        ivTraceDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UserData userData = deliveryDAL.queryById(Integer.parseInt(userid));
                if (userData.getData()!=null){
                    FeedbackData feedbackData = gson.fromJson(userData.getData(),FeedbackData.class);
                    if (feedbackData.getTrace()!=null){
                        feedbackData.setTrace(null);
                        String json = gson.toJson(feedbackData);
                        userData.setData(json);
                        deliveryDAL.updateUser(userData);
                        Log.i("TAG","删除成功");
                        Toast.makeText(getContext(),"删除成功",Toast.LENGTH_SHORT).show();
                        adapter.setExpressList(new ArrayList<>());
                        adapter.notifyDataSetChanged();
                        tvTraceTitle.setText("暂无追踪的快递");
                    }else Log.i("TAG","暂无需要删除的快递1");
                }else Log.i("TAG","暂无需要删除的快递2");
            }
        });
    }

    private List<Map<String, String>> parseTrackingResponse(TrackingResponse response) {
        List<Map<String, String>> expressInfo = new ArrayList<>(); // ...（填充expressInfo的逻辑，与原始代码相同） return expressInfo;
        if (response.getStatus().equals("0")) {
            Map<String, String> status = new ArrayMap<>();
            status.put("查询状态：", "正常");
            Map<String, String> number = new ArrayMap<>();
            number.put("单号：", response.getResult().getNumber());
            Map<String, String> type = new ArrayMap<>();
            type.put("快递公司简称：", response.getResult().getType());
            expressInfo.add(status);
            expressInfo.add(number);
            expressInfo.add(type);
            for (int i = 0; i < response.getResult().getList().size(); i++) {
                Map<String, String> t = new ArrayMap<>();
                t.put("时间：", response.getResult().getList().get(i).getTime());
                Map<String, String> s = new ArrayMap<>();
                s.put("状态：", response.getResult().getList().get(i).getStatus());
                expressInfo.add(t);
                expressInfo.add(s);
            }
        }
        return expressInfo;
    }

    public void updateData(String newTrackingInfo) {
        DeliveryDAL deliveryDAL = new DeliveryDAL(getContext());
        Log.i("TAG","11111");
        List<Map<String,String>> expressInfo = new ArrayList<>();
        FeedbackData feedbackData = gson.fromJson(newTrackingInfo,FeedbackData.class);
        if (feedbackData.getTrace()!=null){
            Log.i("TAG","22222");
            httpGetData = new HttpGetData(feedbackData.getTrace().getNumber()+":"+feedbackData.getTrace().getPhone(),feedbackData.getTrace().getType(),null);
            String responseData = httpGetData.QueryLogistics();
            TrackingResponse response = gson.fromJson(responseData,TrackingResponse.class);
            expressInfo=parseTrackingResponse(response);
            adapter.setExpressList(expressInfo);
            rvTraceData.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
            rvTraceData.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            Log.i("TAG","处理成功");
            tvTraceTitle.setText("我  的  快  递");
        }else tvTraceTitle.setText("暂无追踪快递");
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_trace,container,false);
        initView(v);
        return v;
    }

    private void initView(View v) {
        rvTraceData = (RecyclerView) v.findViewById(R.id.rvTraceData);
        ivTraceDelete = (ImageView) v.findViewById(R.id.ivTraceDelete);
        tvTraceTitle = (TextView) v.findViewById(R.id.tvTraceTitle);
    }
}